package cn.b.sky.mes.hr.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.b.sky.mes.hr.model.Personnel;
import cn.b.sky.mes.hr.model.PersonnelTypeAssign;
import cn.b.sky.mes.hr.model.ShiftingPermission;
import cn.b.sky.mes.hr.model.condition.PersonnelCondition;
import cn.b.sky.mes.hr.model.condition.PersonnelTypeAssignCondition;
import cn.b.sky.mes.hr.service.PersonnelService;
import cn.b.sky.mes.hr.service.PersonnelTypeAssignService;
import cn.b.sky.mes.hr.service.ShiftingPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.user.service.model.UserInfo;

@Controller
@RequestMapping(value = "/personnel/*")
@Slf4j
public class PersonnelController extends SecurityController {

  @Autowired
  private PersonnelService personnelService;

  @Autowired
  private PersonnelTypeAssignService personnelTypeAssignService;

  @Resource
  private ShiftingPermissionService shiftingPermissionService;

  @RequestMapping("personnelIndex")
  public String personnelIndex(Model model, String navTabId) {
    UserInfo curUser = SecurityContextUtil.getCurrentUser();
    model.addAttribute("workCenterTree", personnelService.getWorkCenterTree(this.getSiteCode(), curUser.getUserCode()));
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnel/personnel_index";
  }

  @RequestMapping("personnelListData")
  @ResponseBody
  public DWZResult personnelListData(Model model, String navTabId, PersonnelCondition condition) {

    if (StringUtils.isEmpty(condition.getOrderField())) {
      condition.setOrderField("createDateTime");
    }

    condition.setSiteCode(this.getSiteCode());
    // 获取当前用户的工作中心权限
    List<ShiftingPermission> workCenters = shiftingPermissionService.getPermissionsByUser(this.getSiteCode(),
        SecurityContextUtil.getCurrentUserName(), null);

    if (workCenters == null || workCenters.isEmpty()) {
      condition.setData(new ArrayList<Personnel>());
      condition.setTotalCount(0);
    } else {
      condition.setPermission(workCenters);
      List<Personnel> list = personnelService.getPersonnelListByCondition(condition);
      int count = personnelService.getPersonnelCountByCondition(condition);
      condition.setData(list);
      condition.setTotalCount(count);
    }
    return ajaxDone(condition);
  }

  @RequestMapping("personnelList")
  public String personnelList(Model model, String navTabId, PersonnelCondition condition) {

    condition.setSiteCode(this.getSiteCode());
    // 获取当前用户的工作中心权限
    List<ShiftingPermission> workCenters = shiftingPermissionService.getPermissionsByUser(this.getSiteCode(),
        SecurityContextUtil.getCurrentUserName(), null);

    if (workCenters == null || workCenters.isEmpty()) {
      condition.setData(new ArrayList<Personnel>());
      condition.setTotalCount(0);
    } else {
      condition.setPermission(workCenters);
      List<Personnel> list = personnelService.getPersonnelListByCondition(condition);
      int count = personnelService.getPersonnelCountByCondition(condition);
      condition.setData(list);
      condition.setTotalCount(count);
    }
    model.addAttribute("page", condition);
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnel/personnel_list";
  }

  @RequestMapping("personnel_add")
  public String addPersonnel(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    return "hr/personnel/personnel_add";
  }

  @RequestMapping("savePersonnel")
  @ResponseBody
  public DWZResult savePersonnel(Model model, String rel, String navTabId, String id, Personnel personnel,
      HttpServletRequest request) {
    if (personnel == null) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          SystemConstant.PARAMETERNULL));
    }
    try {
      this.setCreateInfo(personnel);
      personnel.setSiteCode(SecurityContextUtil.getSiteCode());

      if (personnel.getLockFlag() == null) {
        personnel.setLockFlag(0);
      }
      if (StringUtils.isEmpty(id)) {
        personnelService.savePersonnel(personnel);
      } else {
        personnelService.updatePersonnel(personnel);
      }
      return dialogAjaxDone(
          getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "successfulOperation.M"),
          navTabId, null, null, null);
    } catch (Exception e) {
      log.error("{}", e);
      model.addAttribute("message", e.getMessage());
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "failedOperation.M"));
    }
  }

  @RequestMapping("modifyPersonnel")
  public String modifyPersonnel(Model model, String navTabId, String id) {
    Personnel personnel = personnelService.getPersonnelInfo(SecurityContextUtil.getSiteCode(), id);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("personnel", personnel);
    return "hr/personnel/personnel_edit";
  }

  @RequestMapping("validatePersonnelCode")
  @ResponseBody
  public boolean validatePersonnelCode(String personnelCode, Model model) {
    if (!StringUtils.isBlank(personnelCode)) {
      Personnel personnel = personnelService.getPersonnelInfo(SecurityContextUtil.getSiteCode(), personnelCode);
      return personnel == null;
    }
    return true;

  }

  @RequestMapping("deletePersonnel")
  @ResponseBody
  public DWZResult deletePersonnel(String navTabId, Model model, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          SystemConstant.PARAMETERNULL));
    }
    String[] personnelCodes = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(personnelCodes.length);
    boolean hasFail = false;
    for (String personnelCode : personnelCodes) {
      BatchJobReport report = personnelService.deletePersonnel(this.getSiteCode(), personnelCode);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone(request, reports);
    }
  }

  @RequestMapping("personnelSuggest")
  @ResponseBody
  public List<Personnel> personnelSuggest(PersonnelCondition condition) {
    condition.setSiteCode(this.getSiteCode());
    condition.setLockFlag(0);
    //获取当前用户的工作中心权限
    List<ShiftingPermission> workCenters = shiftingPermissionService.getPermissionsByUser(this.getSiteCode(),
        SecurityContextUtil.getCurrentUserName(), 0);
    condition.setPermission(workCenters);
    return personnelService.getPersonnelsSuggestByPermission(condition);
  }

  @RequestMapping("personnelLookUp")
  public String personnelLookUp(Model model, String lookupType,
      @ModelAttribute("condition") PersonnelCondition condition) {
    condition.setSiteCode(getSiteCode());
    condition.setLockFlag(0);

    // 获取当前用户的工作中心权限
    List<ShiftingPermission> workCenters = shiftingPermissionService.getPermissionsByUser(this.getSiteCode(),
        SecurityContextUtil.getCurrentUserName(), null);

    if (workCenters == null || workCenters.isEmpty()) {
      condition.setData(new ArrayList<Personnel>());
      condition.setTotalCount(0);
    } else {
      condition.setPermission(workCenters);
      List<Personnel> list = personnelService.getPersonnelListByCondition(condition);
      int count = personnelService.getPersonnelCountByCondition(condition);
      condition.setData(list);
      condition.setTotalCount(count);
    }
    model.addAttribute("page", condition);
    if (!StringUtils.isBlank(lookupType) && "multi".equals(lookupType)) {
      return "hr/personnel/personnel_lookup_multi";
    }
    return "hr/personnel/personnel_lookup_radio";
  }

  @RequestMapping("getPersonnelTypeAssignByPersonnel")
  @ResponseBody
  public DWZResult getPersonnelTypeAssignByPersonnel(String personnelCode) {
    PersonnelTypeAssignCondition condition = new PersonnelTypeAssignCondition();
    condition.setSiteCode(getSiteCode());
    condition.setPersonnelCode(personnelCode);
    List<PersonnelTypeAssign> ptaList = personnelTypeAssignService.getPersonnelTypeAssignsByCondition(condition);
    return ajaxDone(ptaList);
  }

  @RequestMapping("getPersonnel")
  @ResponseBody
  public Personnel getPersonnel(String personnelCode) {
    return personnelService.getPersonnelInfo(getSiteCode(), StringUtils.upperCase(personnelCode));
  }

  /**
   * 
   * <strong>Title : getPersonnelAndType<br></strong>
   * <strong>Description : </strong>获取人员及人员类型<br> 
   * <strong>Create on : 2016-4-6 上午10:39:51<br></strong>
   * <p>
   * @param personnelCode
   * @return
   * DWZResult
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("getPersonnelAndType")
  @ResponseBody
  public DWZResult getPersonnelAndType(String personnelCode) {
    if (StringUtils.isBlank(personnelCode)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }
    Personnel personnel = personnelService.getPersonnelInfo(getSiteCode(), StringUtils.upperCase(personnelCode));
    List<PersonnelTypeAssign> ptas = personnelTypeAssignService.getPersonnelTypeAssignsByPersonnel(this.getSiteCode(),
        personnelCode);
    personnel.setPtas(ptas);
    return ajaxDone(personnel);
  }

  @RequestMapping("validatePersonnel")
  @ResponseBody
  public boolean validatePersonnel(String personnelCode, String workcenterCode, String originalCode) {

    if (StringUtils.isBlank(personnelCode)) {
      return false;
    }
    //修改校验去掉自己本身
    if (!StringUtils.isBlank(originalCode) && personnelCode.equals(originalCode)) {
      return true;
    }

    Personnel personnel = personnelService.getPersonnelInfo(getSiteCode(), personnelCode);
    if (!StringUtils.isEmpty(workcenterCode)) {
      return personnel != null && personnel.getWorkCenterCode().equalsIgnoreCase(workcenterCode)
          && personnel.getLockFlag() == 0;
    }
    return personnel != null && personnel.getLockFlag() == 0;
  }

}
